<template>
  <div class="shop-list-container">
    <el-card class="shop-list-card" shadow="hover">
      <!-- 卡片头部 -->
      <div class="card-header">
        <span class="title">我的店铺列表</span>
        <el-button type="primary" icon="Plus" @click="handleAddShop">
          新增店铺
        </el-button>
      </div>

      <!-- 搜索区域 -->
      <el-row :gutter="20" class="search-bar">
        <el-col :span="8">
          <el-input
              v-model="searchQuery"
              placeholder="搜索店铺名称/描述"
              clearable
              prefix-icon="Search"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
          />
        </el-col>
        <el-col :span="4" :offset="12">
          <el-button type="success" icon="Refresh" @click="handleSearch">
            重置搜索
          </el-button>
        </el-col>
      </el-row>

      <!-- 店铺卡片列表（淘宝风格） -->
      <div class="shop-cards-container">
        <div
            class="shop-card"
            v-for="shop in shops"
            :key="shop.id"
            @click="handleCardClick(shop)"
        >
          <!-- 店铺图片区域 -->
          <div class="shop-img-container">
            <img
                v-if="shop.logo"
                :src="shop.logo"
                alt="店铺Logo"
                class="shop-logo"
            />
            <div v-else class="no-logo">
              <el-icon class="logo-placeholder"><Shop /></el-icon>
            </div>

            <!-- 状态标签 -->
            <el-tag
                :type="shop.status === '0' ? 'success' : 'info'"
                effect="dark"
                class="status-tag"
            >
              {{ shop.status === '0' ? '营业中' : '休息中' }}
            </el-tag>
          </div>

          <!-- 店铺信息区域 -->
          <div class="shop-info">
            <h3 class="shop-name">{{ shop.shopName }}</h3>
            <p class="shop-desc">{{ shop.shopDesc }}</p>

            <div class="shop-meta">
              <span class="product-count">商品数: {{ shop.productCount }}</span>
              <span class="create-time">创建于: {{ formatDate(shop.createTime) }}</span>
            </div>
          </div>

          <!-- 操作按钮区域 -->
          <div class="shop-actions">
            <el-button size="mini" icon="View" @click.stop="handleView(shop.id)">查看</el-button>
            <el-button size="mini" icon="Edit" @click.stop="handleEdit(shop)">编辑</el-button>
            <el-button size="mini" icon="Delete" type="danger" @click.stop="handleDelete(shop)">删除</el-button>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more-container" v-if="!loading && hasMore">
        <el-button
            type="default"
            icon="RefreshRight"
            @click="loadMore"
            :loading="loadingMore"
        >
          加载更多
        </el-button>
      </div>



      <!-- 没有更多数据 -->
      <div class="no-more" v-if="!hasMore && !loading">
        <p>已经到底啦~</p>
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="店铺详情"
        width="600px"
        :before-close="handleCloseDetailDialog"
    >
      <div v-if="currentShop" class="shop-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="ID">{{ currentShop.id }}</el-descriptions-item>
          <el-descriptions-item label="店铺名称">{{ currentShop.shopName }}</el-descriptions-item>
          <el-descriptions-item label="店铺描述">{{ currentShop.shopDesc }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentShop.createTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentShop.status === '0' ? 'success' : 'info'" effect="dark">
              {{ currentShop.status === '0' ? '营业中' : '休息中' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="商品数量">{{ currentShop.productCount }}</el-descriptions-item>
          <el-descriptions-item label="Logo">
            <img v-if="currentShop.logo" :src="currentShop.logo" width="80" height="80" />
            <span v-else>无Logo</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { AuthService } from '@/service/auth.ts';
import { useRouter } from 'vue-router';
import { Shop } from '@element-plus/icons-vue';

const authService = new AuthService();
const userId = ref(authService.getUserId());
const router = useRouter();

// 店铺数据
const shops = ref([]);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示10个卡片

// 加载状态
const loading = ref(false);
const loadingMore = ref(false);
const hasMore = ref(true);

// 详情对话框相关
const detailDialogVisible = ref(false);
const currentShop = ref(null);

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString();
};

// 获取店铺数据
const getShops = async (append = false) => {
  if (!append) {
    loading.value = true;
  } else {
    loadingMore.value = true;
  }

  try {
    const response = await axios.get(`/api/shop/shopsByUserId/${userId.value}`, {
      params: { pageNum: currentPage.value, pageSize: pageSize.value }
    });

    if (append) {
      shops.value = [...shops.value, ...response.data.records];
    } else {
      shops.value = response.data.records;
    }

    // 判断是否还有更多数据
    if (shops.value.length >= response.data.total) {
      hasMore.value = false;
    } else {
      hasMore.value = true;
    }
  } catch (error) {
    console.error('加载店铺失败:', error);
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getShops(); // 重置搜索后重新获取数据
};

// 加载更多
const loadMore = () => {
  if (loadingMore.value || !hasMore.value) return;
  currentPage.value++;
  getShops(true); // 加载更多时追加数据
};

// 卡片点击事件
const handleCardClick = (shop) => {
  // 点击卡片空白处查看详情
  currentShop.value = shop;
  detailDialogVisible.value = true;
};

// 查看详情（通过按钮）
const handleView = (shopId) => {
  router.push(`/Shop/${shopId}`);
};

// 关闭详情对话框
const handleCloseDetailDialog = (done) => {
  done();
};

// 其他操作
const handleSelectionChange = (val) => console.log('选中:', val);
const handleAddShop = () => console.log('新增店铺');
const handleEdit = (row) => console.log('编辑:', row);
const handleDelete = (row) => console.log('删除:', row);

onMounted(() => {
  getShops();
});
</script>

<style scoped>
.shop-list-container {
  padding: 20px;
}

.shop-list-card {
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.search-bar {
  margin: 16px 20px;
}

/* 店铺卡片容器 */
.shop-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 20px;
}

/* 店铺卡片样式 - 模仿淘宝商品卡片 */
.shop-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.shop-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

/* 店铺图片区域 */
.shop-img-container {
  position: relative;
  width: 100%;
  height: 180px;
  background-color: #f9f9f9;
  overflow: hidden;
}

.shop-logo {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.shop-card:hover .shop-logo {
  transform: scale(1.05);
}

.no-logo {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}

.logo-placeholder {
  font-size: 48px;
  color: #ccc;
}

.status-tag {
  position: absolute;
  top: 10px;
  right: 10px;
}

/* 店铺信息区域 */
.shop-info {
  padding: 12px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.shop-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.shop-desc {
  font-size: 14px;
  color: #666;
  margin: 0 0 12px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  flex: 1;
}

.shop-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
  margin-top: auto;
}

/* 操作按钮区域 */
.shop-actions {
  display: flex;
  justify-content: center;
  gap: 8px;
  padding: 10px 12px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
}

/* 加载更多样式 */
.load-more-container {
  padding: 20px;
  text-align: center;
}

.loading-container {
  padding: 40px;
  text-align: center;
}

.no-more {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* 店铺详情样式 */
.shop-detail {
  padding: 20px 0;
}

.shop-detail img {
  border-radius: 4px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .shop-cards-container {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 10px;
    padding: 10px;
  }

  .shop-img-container {
    height: 120px;
  }

  .shop-name {
    font-size: 14px;
  }

  .shop-desc {
    font-size: 12px;
  }
}
</style>
